package cn.itcast.controller;


import cn.itcast.Role;
import cn.itcast.UserInfo;

import cn.itcast.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 查询所有用户的方法
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws Exception {
        List<UserInfo> userList = userService.findAll();
        ModelAndView mv = new ModelAndView();
        mv.addObject("userList", userList);
        mv.setViewName("user-list");
        return mv;

    }


    /**
     *添加用户
     * @param userInfo
     * @return
     * @throws Exception
     */
    @RequestMapping("/save")
    public String save(UserInfo userInfo) throws Exception {
        userService.save(userInfo);
        return "redirect:findAll";
    }

    /**
     * 根究id查询用户
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/findById")
    public ModelAndView findbyId(String id) throws Exception{
        ModelAndView mv = new ModelAndView();

        UserInfo userInfo = userService.findById(id);
        mv.addObject("user",userInfo);
        mv.setViewName("user-show");
        return mv;
    }

    /**
     * 根据用户ID查询用户，以及用户可以添加的角色。
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/findUserByIdAndAllRole")
    public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id") String userId) throws Exception{
        ModelAndView mv = new ModelAndView();
       // UserInfo user = userService.findById(userId);
        mv.addObject("userId",userId);
       List<Role> otherRoles =  userService.findOtherRoles(userId);
        mv.addObject("roleList",otherRoles);
       mv.setViewName("user-role-add");
       return mv;
    }

    /**
     * 给用户添加角色
     * @param userId
     * @param roleIds
     * @return
     * @throws Exception
     */
    @RequestMapping("/addRoleToUser")
    public String addRoleToUser(@RequestParam(name = "userId",required = true)String userId,
                                @RequestParam(name = "ids",required = true)String[] roleIds)throws Exception{

        userService.addRoleToUser(userId,roleIds);
        return "redirect:findAll";
    }

    /**
     * 批量删除用户
     * @param userIds
     * @return
     */
    @RequestMapping("/delByIds")
    public String delByIds(@RequestParam(name = "ids") String[] userIds) throws Exception{
        userService.delByIds(userIds);
        return "redirect:findAll";
    }
}
